import * as config from 'config';
import { APP_FILTER, APP_GUARD } from '@nestjs/core';
import { MiddlewareConsumer, Module, Res } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthorityGuard } from './guards/authority.guard';
import { IpMiddleware } from './middlewares/ip.middleware';
import { ErrorFilter } from './filters/error/error.filter';
import { TestModule } from './modules/test/test.module';
import { UserModule } from './modules/user/user.module';
import { AuthModule } from './modules/auth/auth.module';
import { IoredisModule } from './modules/ioredis/ioredis.module';
import { RoleModule } from './modules/role/role.module';
import { PermissionModule } from './modules/permission/permission.module';
import { DictModule } from './modules/dict/dict.module';
import { MenuModule } from './modules/menu/menu.module';
import { DictitemModule } from './modules/dictitem/dictitem.module';
import { DepartmentModule } from './modules/department/department.module';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: config.get('db.host'),
      port: config.get('db.port'),
      database: config.get('db.dbname'),
      username: config.get('db.username'),
      password: config.get('db.password'),
      autoLoadEntities: true,
      synchronize: config.get('db.synchronize') // 生产环境中禁止开启
    }),
    IoredisModule,
    AuthModule,
    TestModule,
    UserModule,
    RoleModule,
    PermissionModule,
    DictModule,
    DictitemModule,
    MenuModule,
    DepartmentModule
  ],
  controllers: [AppController],
  providers: [
    AppService,
    {
      provide: APP_GUARD,
      useClass: AuthorityGuard
    },
    {
      provide: APP_FILTER,
      useClass: ErrorFilter
    }
  ]
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(IpMiddleware).forRoutes('*'); // 应用于所有路由
  }
}
